<?php
/**
 * 微信公众平台开发接口
 * User: 王文凡<787802868@qq.com>
 * Date: 2016/7/28 0028
 * Time: 15:31
 */
namespace Mobile\Controller;
use Common\Api\Wechat;
use Think\Controller;

class IndexController extends Controller
{

    protected $weObj;
    protected $ToUserName;//接受方id
    protected $FromUserName;//发送方id
    protected $keyword;//关键词
    protected $msg_type;//消息类型
    const DEFAULT_MSG = '等待处理~~';//默认回复内容
    const MSG_TEXT_TYPE=1;
    const MSG_IMAGE_TEXT_TYPE=2;
    const MSG_IMAGE_TYPE=3;

    /**
     * 获取微信配置文件
     */
    public function _initialize()
    {
        $tokenId = I('get.token');
        $re = M('wechatConfig')->where("token='%s'", $tokenId)->find();
        $config = array(
            'token' => $tokenId, //填写你设定的key
            'encodingaeskey' => $re['encodingaeskey'], //填写加密用的EncodingAESKey
            'appid' => $re['appid'], //填写高级调用功能的app id
            'appsecret' => $re['appsecret'] //填写高级调用功能的密钥
        );
        $this->weObj = new Wechat($config);
    }

    /**
     * 微信开发入口方法
     */
    public function wechat_token()
    {

        $this->weObj->valid();
        $this->msg_type = $this->weObj->getRev()->getRevType();
        $this->ToUserName = $this->weObj->getRevTo();
        $this->FromUserName = $this->weObj->getRevFrom();
        $this->keyword = trim($this->weObj->getRevContent());
        switch ($this->msg_type) {
            case Wechat::MSGTYPE_TEXT:
                //接受文本消息
                if ($this->update_label($this->keyword)) return false;
                $this->reply_text(self::DEFAULT_MSG);
                break;
            case Wechat::MSGTYPE_EVENT:
                //关注事件
                $this->attention($this->ToUserName, $this->FromUserName);
                break;
            case Wechat::MSGTYPE_IMAGE:
                //TODO:图片消息
                break;
            case Wechat::MSGTYPE_LOCATION:
                //地理位置消息
                $this->location($this->ToUserName, $this->FromUserName);
                break;
            default:
                $this->reply_text(self::DEFAULT_MSG);
        }

    }

    /**接受地理位置处理
     * @param $ToUserName
     * @param $FromUserName
     */
    public function location($ToUserName, $FromUserName)
    {

        $re = M("Member")->where("open_id='%s'", $FromUserName)->find();
        if ($re) {
            $geo = $this->weObj->getRevGeo();//地理位置信息
            $ldata['Location_X'] = $geo['x'];
            $ldata['Location_y'] = $geo['y'];
            $ldata['Scale'] = $geo['scale'];
            $ldata['label'] = $geo['label'];
            $ldata['wechat_id'] = $FromUserName;
            $ldata['uid'] = $re['id'];
            $ldata['sr_time'] = time();
            $ldata['gl_time'] = strtotime(date('Y-m-d'));
            if (M('location')->add($ldata)) {
                $content = '发送地理位置成功!';

            } else {
                $content = '发送失败，请重新发送!';
            }

        } else {
            $content = '只有绑定的员工账号才能记录地理位置信息!';
        }
        $this->reply_text($content);

    }

    /**
     * 接关注事件进行处理
     * @var param string $ToUserName
     * @var param string $FromUserName
     * @return boolean
     */
    private function attention($ToUserName, $FromUserName)
    {

        $eventArray = $this->weObj->getRevEvent();
        if (!empty($eventArray)) {

            switch ($eventArray['event']) {

                case 'subscribe' : //关注
                    return $this->is_gz($FromUserName) ? $this->reply_text('欢迎关注天晨定制!!') : false;
                    break;

                case 'unsubscribe': //取消关注
                    return $this->un_is_gz($FromUserName);
                    break;

                case 'SCAN':  //场景
                    $sceneKey = $this->weObj->getRevSceneId();
                    return (!empty($sceneKey) && $sceneKey !== 0) ? $this->update_label($sceneKey, $FromUserName) : false;
                    break;
            }
        }

    }

    /**场景处理
     * @param $keyword
     * @param $openid
     * @return mixed|booleam
     */
    private function update_label($keyword, $openid)
    {
        if (substr($keyword, 0, 1) == '#') {
            $groupid = substr($keyword, 1);
            if ($this->weObj->updateGroupMembers($groupid, $openid)) {
                return $this->reply_text('进入分组成功');
            }
        } else {
            $data = $this->execution_keyword($keyword);
            if ($data == null) return false;
            switch ($data['msg_type']) {
                case self::MSG_TEXT_TYPE :
                    //TODO: 文本消息处理
                    return $this->reply_text($data['text_msg']);//回复文本消息
                    break;
                case self::MSG_IMAGE_TEXT_TYPE :
                    //TODO: 图文消息处理
                    $datas=array();
                    $newData['Title']=$data['title'];
                    $newData['Description']=$data['msg_desc'];
                    $newData['PicUrl']=$data['img_msg'];
                    $newData['Url']=$data['msg_link'];
                    $datas[]=$newData;
                    return $this->reply_img_text($datas);
                case MSG_IMAGE_TYPE :
                    //TODO: 图片消息处理

            }

        }
    }

    /**发送图文
     * @param $newData
     * @return booleam
     */
    private function reply_img_text($newData)
    {
        return $this->weObj->news($newData)->reply();
    }

    /**发送文本消息
     * @param string $msg
     * @return booleam
     */
    private function reply_text($msg)
    {
        return $this->weObj->text($msg)->reply();
    }

    /**搜索关键词
     * @param  string $keyword
     * @return booleam|array
     */
    private function execution_keyword($keyword)
    {
        $msg_data = M('Keywords')->where("keyword='%s'", $keyword)->find();
        return !empty($msg_data) ? $msg_data : false;
    }

    /**关注后执行的数据
     * @param $FromUserName
     * @return booleam
     */
    private function is_gz($FromUserName)
    {
        if (M('Fans')->where("openid='%s'", $FromUserName)->find()) {
            if (M('Fans')->where("openid='%s'", $FromUserName)->save(['is_gz' => 1])) {
                return true;
            } else {
                return false;
            }
        } else {
            $userData = $this->getUserInfo($FromUserName);
            $userData['is_gz'] = 1;
            $userData['gz_time'] = time();
            return (M('Fans')->add($userData)) ? true : false;
        }
    }

    /**取消关注处理
     * @param $FromUserName
     * @return booleam
     */
    private function un_is_gz($FromUserName)
    {
        (M('Fans')->where("openid='%s'", $FromUserName)->save(['is_gz' => 0, 'update_time' => time()])) ? true : false ;

    }

    /**获取微信用户信息
     * @param $openid
     * @return mixed
     */
    protected function getUserInfo($openid)
    {
        $userinfo = $this->weObj->getUserInfo($openid);
        $userData['openid'] = $userinfo['openid'];
        $userData['nickname'] = $userinfo['nickname'];
        $userData['sex'] = $userinfo['sex'];
        $userData['city'] = $userinfo['city'];
        $userData['headimgurl'] = $userinfo['headimgurl'];
        return $userData;

    }



}